package com.shelpe.services.sycm.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shelpe.services.sycm.dao.CookieMapper;
import com.shelpe.services.sycm.dao.RptItemsMapper;
import com.shelpe.services.sycm.model.Cookie;
import com.shelpe.services.sycm.model.CookieExample;
import com.shelpe.services.sycm.model.RptItems;
import com.shelpe.services.sycm.utils.HttpClient;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/sycmservice")
public class SycmController {

	static String HOST = "https://bda.sycm.taobao.com";
	
	static String TOKEN = "9c1466cb2";
	
	@Autowired
	CookieMapper cookieMapper;
	
	@Autowired
	RptItemsMapper rptItemsMapper;
	
	@RequestMapping("/get/{id}")
	public @ResponseBody Cookie sycm(@PathVariable("id")Integer id){
		log.info("........");
		return cookieMapper.selectByPrimaryKey(id);
	}

	/**
	 * 
	 * @param dateRange
	 * @param dateType
	 * @param device
	 * @return
	 */
	@RequestMapping("/get/{id}/flow/summary/getGeneral.jsonp")
	public @ResponseBody String a(@PathVariable("id")Long id, @RequestParam String dateRange, @RequestParam String dateType, @RequestParam Integer device){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		params.put("device", device);
		return getData(id, "/flow/summary/getGeneral.jsonp", params);
	}
	
	/**
	 * 获取店铺流量信息
	 * @param dateRange
	 * @param dateType
	 * @param device
	 * @return
	 */
	@RequestMapping("/get/{id}/flow/getSourceTop.jsonp")
	public @ResponseBody String b(@PathVariable("id")Long id, @RequestParam String dateRange, @RequestParam String dateType, @RequestParam(required = false) Integer top){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		if(top!=null){
			params.put("device", top);
		}
		return getData(id, "/flow/getSourceTop.jsonp", params);
	}
	
	/**
	 * 获取店铺交易信息
	 * @param id
	 * @param dateRange
	 * @param dateType
	 * @param device
	 * @return
	 */
	@RequestMapping("/get/{id}/tradinganaly/overview/get_summary.jsonp")
	public @ResponseBody String d(@PathVariable("id")Long id, @RequestParam String dateRange, @RequestParam String dateType, @RequestParam Integer device){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		params.put("device", device);
		return getData(id, "/tradinganaly/overview/get_summary.jsonp", params);
	}
	
	/**
	 * 获取店铺宝贝效果数据 
	 * @return
	 */
	@RequestMapping("/users/{id}/itemsEffectDetails")
	public @ResponseBody String c(@PathVariable("id")Long id, @RequestParam String dateRange, @RequestParam String dateType, 
			@RequestParam Integer device, @RequestParam(required = false)String orderDirection, @RequestParam(required = false)String orderField,
			@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "500") Integer pageLimit, 
			@RequestParam Integer type, @RequestParam(required = false) String keywords, @RequestParam(defaultValue = "false") boolean save){
		log.info("....details....");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		params.put("device", device);
		params.put("page", page);
		params.put("pageLimit", pageLimit);
		params.put("type", type);
		if(orderDirection!=null){
			params.put("orderDirection", orderDirection);
		}if(orderField!=null){
			params.put("orderField", orderField);
		}if(keywords!=null){
			params.put("keywords", keywords);
		}
		params.put("device", device);
		
		String returnJson = getData(id, "/items/effect/getItemsEffectDetail.jsonp", params);
		
		if(save){
			if(returnJson.contains("content")){
				JSONObject obj = JSON.parseObject(returnJson);
				JSONArray data = obj.getJSONObject("content").getJSONObject("data").getJSONArray("data");
				JSONObject item = null;
				RptItems record = null;
				for(Iterator iter = data.iterator(); iter.hasNext();){
					item = (JSONObject)iter.next();
					record = new RptItems();
					rptItemsMapper.insertSelective(record);
				}
			}
		}
		return returnJson;
	}

	/**
	 * 店铺访客时段分析
	 * @param id
	 * @param dateRange
	 * @param dateType
	 * @param device
	 * @return
	 */
	@RequestMapping("/get/{id}/visitor/distribution/listPeriods.jsonp")
	public @ResponseBody String e(@PathVariable("id")Long id, @RequestParam String dateRange, @RequestParam String dateType,
			@RequestParam Integer device, @RequestParam(required = false)String index ){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		params.put("device", device);
		if(index!=null){
			params.put("index", index);
		}
		return getData(id, "/visitor/distribution/listPeriods.jsonp", params);
	}
	
	/**
	 * 店铺访客地域分析
	 * @param id
	 * @param dateRange
	 * @param dateType
	 * @param device
	 * @return
	 */
	@RequestMapping("/get/{id}/visitor/distribution/listAreas.jsonp")
	public @ResponseBody String f(@PathVariable("id")Long userId, @RequestParam String dateRange, @RequestParam String dateType,
			@RequestParam Integer device){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		params.put("device", device);
  		return getData(userId, "/visitor/distribution/listAreas.jsonp", params);
	}

	/**
	 * 店铺访客特征分析
	 * @param id
	 * @param dateRange
	 * @param dateType
	 * @param device
	 * @return
	 */
	@RequestMapping("/get/{id}/visitor/distribution/listFeatures.jsonp")
	public @ResponseBody String j(@PathVariable("id")Long id, @RequestParam String dateRange, @RequestParam String dateType,
			@RequestParam Integer device){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		params.put("device", device);
  		return getData(id, "/visitor/distribution/listFeatures.jsonp", params);
	}

	/**
	 * 店铺综合数据
	 * @param id
	 * @param dateRange
	 * @param dateType
	 * @return
	 */
	@RequestMapping("/get/{id}/summary/getShopSummary.jsonp")
	public @ResponseBody String g(@PathVariable("id")Long id, @RequestParam String dateRange, @RequestParam String dateType){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		return getData(id, "/summary/getShopSummary.jsonp", params);
	}
	
	/**
	 * 交易终端数据
	 * @param id
	 * @param dateRange
	 * @param dateType
	 * @return
	 */
	@RequestMapping("/get/{id}/tradinganaly/constitute/getDeviceDetail.jsonp")
	public @ResponseBody String h(@PathVariable("id")Long id, @RequestParam String dateRange, @RequestParam String dateType){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dateRange", dateRange);
		params.put("dateType", dateType);
		return getData(id, "/tradinganaly/constitute/getDeviceDetail.jsonp", params);
	}
	
	private String getData(Long id, String path, Map<String, Object> params){
		Cookie cookie = null;
		CookieExample example = new CookieExample();
		example.createCriteria().andTbUserIdEqualTo(id);
		example.setOrderByClause("id desc");
		List<Cookie> cookies = cookieMapper.selectByExampleWithBLOBs(example);
		if(cookies!=null){
			if(cookies.size() > 0){
				cookie = cookies.get(0);
				log.info("cookie id:{}", cookie.getId());
			}
		}
		if(cookie==null){
			return "cookie is null!";
		}
		//cookie = cookieMapper.selectByPrimaryKey(id.intValue());
		StringBuffer sb = new StringBuffer();
		sb.append(HOST)
		.append(path)
		.append("?sycmToken="+TOKEN);
		for(String key : params.keySet()){
			sb.append("&").append(key).append("=").append(params.get(key));
		}
		log.info("request uri:{}", sb.toString());
		log.info("cookie view:{}", cookie.getCookieView());
		return requestGet(sb.toString(), cookie.getCookieView());
	}
	
	private String requestGet(String uri, String cookie){
		String response = null;
		try {
			response = HttpClient.get(uri, cookie);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(response.startsWith("onJSONPCallback")){
			response = response.substring("onJSONPCallback(".length(), response.length() - 2);
		}
		if(response.startsWith("callback")){
			response = response.substring("callback(".length(), response.length() - 2);
		}
		return response.trim();
	}
	
}
